package cn.ly.spring4.aop.annot;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

//把这个类声明为一个切面：需要把该类放入到IOC容器中、再声明为一个切面
@Aspect
@Component
public class MethodTest {
	
	private final Map<String,Long> map = new HashMap<String,Long>();
	
	//声明该方法是一个前置通知：在目标方法开始之前执行
	@Before("execution( * cn.ly.spring4.aop.LoginAction.*(..))")
	public void beforeMethod(JoinPoint point){
		String objMethod = getMethodName(point);
		long startTime = new Date().getTime();
		map.put(objMethod, startTime);
	}
	
	//声明该方法是一个前置通知：在目标方法开始之前执行
	@After("execution( * cn.ly.spring4.aop.LoginAction.*(..))")
	public void afterMethod(JoinPoint point){
		String objMethod = getMethodName(point);
		long startTime = map.get(objMethod);
		long endTime = new Date().getTime();
		System.out.println(objMethod + "执行所用时间：" + (endTime - startTime) + "毫秒");
		map.remove(objMethod);
	}
	
	private String getMethodName(JoinPoint point){
		String objMethod = point.getTarget().getClass() + ";method " + point.getSignature().getName() + ";params ";
		Object[] params = point.getArgs();
		for(Object o : params){
			objMethod += o.getClass() + ",";
		}
		objMethod = objMethod.replaceAll("class ", "");
		if(objMethod.endsWith(",")){
			objMethod = objMethod.substring(0, objMethod.lastIndexOf(","));
		}
		return objMethod;
	}
	
	

}
